package com.atguigu.springcloud.service.impl;

import com.atguigu.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author yanglin
 * @create 2023-11-11 15:52 星期六
 * description:
 */
@Service
public class PaymentServiceImpl implements PaymentService {
    @Override
    public String paymentInfoOk(Integer id) {
        return "线程池： " + Thread.currentThread().getName() + "payment_ok,id = " + id;
    }


    /**
     * paymentInfoTimeout()出现异常或该方法的处理时长超过3000毫秒，则使用备选方案paymentInfoTimeoutHandler()
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    @Override
    public String paymentInfoTimeout(Integer id) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int timeout = 2;
        
        //测试算数异常是否启用备选方案
        //int num = 10 / 0;
        
        return "线程池： " + Thread.currentThread().getName() + "payment_timeout,id = " + id + " 耗时" + timeout + "秒钟";
        //return "线程池： " + Thread.currentThread().getName() + "payment_timeout,id = " + id;
    }
    
    /**
     * paymentInfoTimeout方法出错后的备选方案
     * @return
     */
    public String paymentInfoTimeoutHandler(Integer id){
        return "系统繁忙，请稍后再试";
    }


    //以下测试服务熔断

    /**
     * circuitBreaker.enable：是否开启断路器
     * circuitBreaker.requestVolumeThreshold：请求次数
     * circuitBreaker.sleepWindowInMilliseconds：时间窗口期
     * circuitBreaker.errorThresholdPercentage：失败率达到多少后跳闸
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerHandler",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")
    })
    @Override
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0){
            throw  new RuntimeException("***id不能小于0");
        }
        String serialNumber = UUID.randomUUID().toString();
        return Thread.currentThread().getName() + "\t" + "流水号：" + serialNumber;
    }
    
    
    public String paymentCircuitBreakerHandler(Integer id){
        return "当前服务过载或者发生异常，已被熔断";
    }
}
